from db import db_work
from api import web_api
from threading import Thread
from datetime import datetime

list_login=[]
count_talk_people=0
count_people=0
lis=[]
path=r'D:\pycharm\华清远见\我的项目-多人聊天室\db\save'
#没连接一个客户端就会创建一个新的该线程
def client_(conn,post_id,count_talk):
    global lis
    global list_login
    global count_people
    global count_talk_people
    dic={}
    user_num=None
    is_private_message=True
    try:
        while True:
            dic=web_api.recv_mes(conn)
            if dic.get('mode')=='register':
                user_num=dic.get('user_num')
                if db_work.select_user_num(user_num):
                    user_name=dic.get('user_name')
                    user_password=dic.get('user_password')
                    db_work.register_user(user_name,user_num,user_password)
                    code='200'
                    msg='用户创建成功成功'
                    time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    log=f'[{post_id},({time}),成功创建一个账号]'
                else:
                    user_name=None
                    code='400'
                    msg='账号以存在'
                    time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    log=f'[{post_id},({time}),尝试创建一个账号，但是失败了]'
                data=web_api.get_response_dic(mode=dic.get('mode'),code=code,user_name=user_name,msg=msg,time=time)
                web_api.send_mes(conn,data)
                print(log)
            elif dic.get('mode')=='login':
                user_num = dic.get('user_num')
                user_password=dic.get('user_password')
                if db_work.select_user_num_and_password(user_num,user_password):
                    user_name = db_work.get_username(user_num)
                    if web_api.is_num(user_num,list_login):
                        data = web_api.get_response_dic(mode='login',code=400,user_name=user_name,msg='账号已登陆',time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                        web_api.send_mes(conn,data)
                        continue
                    list_login.append({'conn':conn,'user_num':user_num})
                    code='200'
                    msg='登录成功'
                    time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    count_people+=1
                    log=f'[{post_id},({time}),登录成功,当前在线人数{count_people}]'
                else:
                    code = '400'
                    user_name = None
                    msg = '登录失败'
                    time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    log = f'[{post_id},({time}),尝试登录但是失败了]'
                data=web_api.get_response_dic(mode=dic.get('mode'),code=code,user_name=user_name,msg=msg,time=time)
                web_api.send_mes(conn, data)
                print(log)
            elif dic.get('mode')=='talk':
                if count_talk==0:

                    lis.append({'conn': conn, 'post_id': post_id, 'user_name': dic.get('user_name')})
                    count_talk=1
                    count_talk_people += 1
                    time=datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    log = f"[{dic.get('user_name')},({time}),进入聊天室,聊天室当前在线人数{count_talk_people}]"
                    data=web_api.get_response_dic(code='200',mode='talk',user_name=dic.get('user_name'),msg=f"{dic.get('user_name')}进入聊天室",time=time)
                    for i in lis:
                        web_api.send_mes(i['conn'], data)
                    print(log,'>>>>>聊天室消息')
                    continue
                if dic.get('msg')=='exit':
                    count_talk=0
                    data = web_api.get_response_dic(code='404', mode='talk', user_name=dic.get('user_name'),
                                                    msg=f'已退出聊天室', time=dic.get('time'))
                    web_api.send_mes(conn, data)
                    lis=[item for item in lis if item['conn'] != conn]
                    count_talk_people-=1
                    data = web_api.get_response_dic(code='200', mode='talk', user_name=dic.get('user_name'),msg=f"{dic.get('user_name')}离开聊天室", time=dic.get('time'))
                    for i in lis:
                        web_api.send_mes(i['conn'], data)
                    log = f"[{dic.get('user_name')},({datetime.now().strftime('%Y-%m-%d %H:%M:%S')})离开·,当前聊天室人数{count_talk_people}]"
                    print(log,'>>>>>聊天室消息')
                    continue

                data=web_api.get_response_dic(code='200',mode='talk',user_name=dic.get('user_name'),msg=dic.get('msg'),time=dic.get('time'))
                for i in lis:
                    web_api.send_mes(i['conn'], data)
            elif dic.get('mode')=='file':
                file_size=dic.get('file_size')
                file_name = dic.get('file_name')
                db_work.in_save(path,file_size,file_name,conn)
                data=web_api.get_response_dic(code=200,mode='file',user_name=dic.get('user_name'),msg='文件写入成功',time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
                web_api.send_mes(conn,data)
            elif dic.get('mode')=='private_message':
                if is_private_message:
                    first_contact_talk(conn,dic)
                    is_private_message=False
                else:
                    is_private_message=contact_talk(conn,dic)
            elif dic.get('mode')=='contacts':
                contacts(conn,dic)
            elif dic.get('mode')=='add_contact':
                add_contact(conn,dic)
            else:
                for i in list_login:
                    if i['user_num']==user_num:
                        list_login.remove(i)
                count_people-=1
                print(f'{post_id}退出了登录,当前在线人数{count_people}>>>>>在线用户信息')
    except (AttributeError,ConnectionResetError):
        l=len(list_login)
        for i in list_login:
            if i['user_num'] == user_num:
                list_login.remove(i)
        if l==len(list_login):
            return
        count_people-=1
        lis = [item for item in lis if item['conn'] != conn]
        if count_talk==1:
            count_talk_people-=1
            print(f"{dic.get('user_name')}因为外部断开连接,聊天室当前在线人数{count_talk_people}>>>>>聊天室信息")
            data = web_api.get_response_dic(code='200', mode='talk', user_name=dic.get('user_name'),
                                            msg=f"{dic.get('user_name')}离开聊天室", time=dic.get('time'))
            for i in lis:

                web_api.send_mes(i['conn'], data)
        print(f'{post_id}因为外部断开连接,当前在线人数{count_people}>>>>>在线用户信息')
        conn.close()


'''
通讯录
'''
def contacts(conn,dic):
    user_name = db_work.get_username(dic.get('user_num'))
    lis = db_work.get_contacts(dic.get('user_num'), user_name)
    data = web_api.get_response_dic(code='200', mode='contacts', user_name=user_name, msg=lis,
                                    time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
    web_api.send_mes(conn, data)
'''
添加联系人
'''
def add_contact(conn,dic):
    contact_num=dic.get('contact_num')
    user_num=dic.get('user_num')
    if not db_work.select_user_num(contact_num):
        db_work.in_contacts(user_num,contact_num)
        code='200'
        msg='联系人添加成功'
    else:
        code = '400'
        msg = '未找到该联系人'
    data = web_api.get_response_dic(code=code, mode='add_contact', user_name=db_work.get_username(user_num),msg=msg, time=dic.get('time'))
    print(data)
    web_api.send_mes(conn, data)

'''
处理私信
'''
def contact_talk(conn,dic):
    content = dic.get('msg')
    if content=='exit':
        data=web_api.get_response_dic(made='200',code='private_message',user_name='',msg={'content':'exit'},time=dic.get('time'))
        web_api.send_mes(conn,data)
        return True
    user1_num=dic.get('user1')
    user2_num=dic.get('user2')
    user_name=db_work.get_username(user2_num)

    time=dic.get('time')
    for i in list_login:
        if i.get('user_num') == user2_num:
            data=web_api.get_response_dic(made='200',code='private_message',user_name=user_name,msg={'user_num':user1_num,'content':content},time=dic.get('time'))
            web_api.send_mes(i.get('conn'), data)
    db_work.message_in_file(user1_num,user2_num,content,time)
    return False
'''
此时，user_num进入与contact_num聊天的页面，该函数为加载出历史聊天记录
'''
def first_contact_talk(conn,dic):
    user1_num=dic.get('user1')
    user2_num=dic.get('user2')
    user_name=db_work.get_username(user1_num)
    lis_data = db_work.message_out_file(user1_num, user2_num)
    data=web_api.get_response_dic(code='200',mode='private_message',user_name=user_name,msg=lis_data,time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

    web_api.send_mes(conn, data)







if __name__ == '__main__':

    sock = web_api.server_create()
    count_talk=0
    while True:
        conn,post_id=sock.accept()
        Thread(target=client_,args=(conn,post_id,count_talk)).start()